package com.newlink.building.activities.main.settings.fragments

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.newlink.building.R
import com.newlink.building.activities.main.settings.viewmodels.UpdateSettingsViewModel
import com.newlink.building.bean.Module_Phone_VersionBean
import com.newlink.building.databinding.SettingsUpdateFragmentBinding
import com.newlink.building.utils.Module_Phone_DeviceUtils
import com.newlink.building.utils.Module_Phone_Event
import com.newlink.building.widget.Module_Phone_UpdateDialog
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.linphone.core.tools.Log

/**
 * @Author: Jake
 * @Date: 2023/1/28
 * @Description:
 */
class Module_Phone_UpdateSettingsFragment : Module_Phone_GenericSettingFragment<SettingsUpdateFragmentBinding>() {

    private lateinit var mViewModel: UpdateSettingsViewModel
    private var lastClickTime: Long = 0

    override fun getLayoutId(): Int = R.layout.settings_update_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = ViewModelProvider(this)[UpdateSettingsViewModel::class.java]
        binding.apply {
            lifecycleOwner = viewLifecycleOwner
            viewModel = mViewModel

            setBackClickListener {
                goBack()
            }

            setOnUpdateClick {
//                Toast.makeText(activity, "update", Toast.LENGTH_SHORT).show()
                val clickTime = System.currentTimeMillis() / 1000
                if (clickTime - lastClickTime < 8) {
                    Toast.makeText(activity, "正在检测新版本", Toast.LENGTH_SHORT).show()

                    return@setOnUpdateClick
                }

                GlobalScope.launch(Dispatchers.IO) {
                    Module_Phone_DeviceUtils.checkNewVersion { code, msg ->
                        try {
                            val versionBean =
                                Gson().fromJson(msg, Module_Phone_VersionBean::class.java)

                            Log.e("jake", "网络版本号:${versionBean.version_code}")
                            Log.e(
                                "jake",
                                "本地版本号:${Module_Phone_DeviceUtils.getAppVersion(requireContext())}"
                            )

                            GlobalScope.launch(Dispatchers.Main) {
                                if (versionBean.version_code.toInt() > Module_Phone_DeviceUtils.getAppVersion(
                                        requireContext()
                                    )
                                ) {
                                    showUpdateDialog(versionBean)
                                } else {
                                    Toast.makeText(
                                        activity,
                                        "当前已经是最新版本",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            }
                        } catch (e: Exception) {
                            GlobalScope.launch(Dispatchers.Main) {
                                Toast.makeText(activity, "检测新版本失败", Toast.LENGTH_SHORT)
                                    .show()
                            }

                            println(e)
                        }
                    }
                    lastClickTime = clickTime / 1000
                }
            }
        }
    }

    private fun showUpdateDialog(updateInfo: Module_Phone_VersionBean) {
        Log.e("jake", " showUpdateDialog $updateInfo")
        Module_Phone_UpdateDialog.Builder(requireContext())
            .setVersionName(updateInfo.version_code)
            .setForceUpdate(false)
            .setUpdateLog(updateInfo.change_log)
            .setDownloadUrl(updateInfo.download_file_address)
            .setFileMd5(updateInfo.download_file_md5)
            .show()
    }

    override fun goBack() {
        exitPage()
    }

    private fun exitPage() {
        sharedViewModel.hideNavigationBar.value = false
        sharedViewModel.jumpToSettingsPage.value = Module_Phone_Event(true)
    }
}
